<?php
namespace app\erp\model;

use app\jun\controller\Api;
use think\Model;
use traits\model\SoftDelete;
use think\Cache;

class Returneddb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';

    protected $pk = 'returned_id';

    protected $name = 'returned';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i',
        'delete_time' => 'timestamp:Y-m-d',
        'back_receive_time' => 'timestamp:Y-m-d H:i',
        'back_express_time' => 'timestamp:Y-m-d H:i',
        'shopping_time' => 'timestamp:Y-m-d H:i',
        'state_time' => 'timestamp:Y-m-d H:i'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id',
        'shopping_state' => 1,
        'returned_uid' => MEMBER_ID,
        'back_receive' => 1,
        'is_send_back',
        'back_express_time'
    ];

    protected function setSiteIdAttr($value)
    {
        if (! $value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    public $get_returned_id = '';

    public function setStateTimeAttr()
    {
        if (isset($this->param['returned_state']) && $this->param['returned_state'] != 1) {
            return time();
        }
    }

    public function setShoppingTimeAttr()
    {
        if (isset($this->param['shopping_state']) && $this->param['shopping_state'] == 2) {
            return time();
        }
    }

    public function setBackExpressTimeAttr()
    {
        if (isset($this->param['is_send_back']) && $this->param['is_send_back'] == 2) {
            return time();
        }
        if (isset($this->param['back_express_no']) && $this->param['back_express_no'] != '' && isset($this->param['back_express']) && $this->param['back_express'] != '') {
            return time();
        }
    }

    public function setBackReceiveTimeAttr()
    {
        if (isset($this->param['is_send_back']) && $this->param['is_send_back'] == 3) {
            return time();
        }
    }

    public function setIsSendBackAttr()
    {
        if (isset($this->param['is_send_back']) && $this->param['is_send_back'] != '') {
            return $this->param['is_send_back'];
        }
        if (isset($this->param['back_express_no']) && $this->param['back_express_no'] != '' && isset($this->param['back_express']) && $this->param['back_express'] != '') {
            return 2;
        } else {
            return 1;
        }
    }

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeReturnedId($query, $returned_id)
    {
        $query->where('returned_id', $returned_id);
    }

    public function scopeReturnedType($query, $returned_type)
    {
        $query->where('returned_type', $returned_type);
    }
	public function scopeOutOrderNo($query, $out_order_no) {
		$query->where ( 'out_order_no', 'like', '%' . $out_order_no . '%' );
	}
    public function scopeOrderNo($query, $order_no)
    {
        $query->where('order_no', 'like', '%' . $order_no . '%');
    }

    public function scopeGoodsSku($query, $goods_sku)
    {
        $query->where('goods_sku', 'like', '%' . $goods_sku . '%');
    }
    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        $query->where('partner_id', PARTNER_ID);
        if (! empty(SITE_ID)) {
            $query->where('site_id', SITE_ID);
        } else {
            $query->where('site_id', 'null');
        }
        if (isset($this->param['returned_id']) && $this->param['returned_id'] != '') {
            $query->returnedId($this->param['returned_id']);
        }
        if (isset($this->param['returned_type']) && $this->param['returned_type'] != '') {
            $query->returnedType($this->param['returned_type']);
        }
        if (isset($this->param['order_no']) && $this->param['order_no'] != '') {
            $query->orderNo($this->param['order_no']);
        }
        if (isset ( $this->param ['out_order_no'] ) && $this->param ['out_order_no']) {
			$query->outOrderNo ( $this->param ['out_order_no'] );
		}
        if (isset($this->param['goods_sku']) && $this->param['goods_sku'] != '') {
            $query->goodsSku($this->param['goods_sku']);
        }
    }
    // 软删除
    public function ajaxDelete()
    {
        if (isset($this->param['returned_id'])) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('returned_id', 'IN', $this->param['returned_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('returned_id', 'IN', $this->param['returned_id']);
                }, true);
            }
            Cache::clear('returned');
            return 'success';
        }
    }
    // 北京政采 保存运单
    public function ajaxSaveBj($out_apply_id)
    {
        $this->useGlobalScope(false)->where('out_apply_id',$out_apply_id)->update($this->param);
        Cache::clear('returned');
        return 'success';
    }
    // 保存数据
    public function ajaxSave()
    {
        if (isset($this->param['returned_id']) && $this->param['returned_id'] != '') {
            $returned_id = $this->param['returned_id'];
            $get_returned = $this->ajaxFind();
            $orderdb = new Orderdb();
            $orderdb->param['order_no'] = $get_returned['order_no'];
            $get_order = $orderdb->ajaxFind();
            $cartdb = new Cartdb();
            $cartdb->param['order_no'] = $get_returned['order_no'];
            $cartdb->param['goods_sku'] = $get_returned['goods_sku'];
            $get_cart = $cartdb->ajaxFind();
            unset($this->param['returned_id']);
            // 添加邮寄地址
            if (isset($this->param['shopping_state']) && $this->param['shopping_state'] == 2) {
                $expressdb = new Expressdb();
                $temp['express_no'] = $this->param['express_no'];
                $temp['express'] = $this->param['express'];
                $temp['depot_id'] = $this->param['depot_id'];
                $temp['order_no'] = $get_returned['order_no'];
                $temp['cart_ids'] = $get_cart['cart_id'];
                $temp['receipt_member_id'] = $get_order['member_id'];
                $temp['is_exchange'] = 2;
                $expressdb->param = $temp;
                $expressdb->ajaxSave();
                $this->param['express_id'] = $expressdb->lastId;
                // 购物车设置退换货状态
                $cartdb->param['cart_id'] = $get_cart['cart_id'];
                $cartdb->param['returned_state'] = 6;
                $cartdb->param['order_no'] = $get_returned['order_no'];
                $cartdb->param['goods_sku'] = $get_returned['goods_sku'];
                $cartdb->param['express_id'] = $expressdb->lastId;
                $cartdb->setReturned();
            }
            if (isset($this->param['returned_state'])) {
                $orderdb = new Orderdb();
                $orderdb->param['order_no'] = $get_returned['order_no'];
                $orderdb->param['event'] = 'returned_refuse';
                $orderdb->param['post_data']['goods_sku'] = $get_returned['goods_sku'];
                if ($this->param['returned_state'] == 3) {
                    $orderdb->param['post_data']['returned_state'] = - 1;
                } else {
                    if ($get_returned['returned_type'] == 1) {
                        $orderdb->param['post_data']['returned_state'] = 3;
                    } else {
                        $orderdb->param['post_data']['returned_state'] = 5;
                    }
                }
                $orderdb->editOrder();
            }
            if (isset($this->param['is_send_back'])) {
                if ($this->param['is_send_back'] == 2) {
                    $this->param['back_express_time'] = time();
                }
                if ($this->param['is_send_back'] == 3) {
                    $this->param['back_receive_time'] = time();
                }
            }
            if (isset($this->param['returned_state']) && $this->param['returned_state'] != 1) {
                $this->param['state_time'] = time();
            }
            if (isset($this->param['shopping_state']) && $this->param['shopping_state'] == 2) {
                $this->param['shopping_time'] = time();
            }
            $this->save($this->param, [
                'returned_id' => $returned_id
            ]);
            $jApi = new Api();
            $jApi->isAfterSale($returned_id);
        } else {
            $this->allowField(true)->save($this->param);
            $this->get_returned_id = $this->returned_id . '_' . $this->order_no;
        }
        Cache::clear('returned');
        return 'success';
    }

    public function ajaxFind()
    {
        $data = $this->find();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = array();
        }
        return $data;
    }

    public function ajaxLog()
    {
        $data = $this->find();
        if (! $data) {
            $log = '';
        } else {
            $data = $data->toArray();
            $data = $this->handleData($data);
            $type_text = $data['returned_type'] == 1 ? '退货' : '换货';
            $log = $data['create_time'] . '：申请' . $type_text;
            if ($data['is_send_back'] >= 2) {
                $log .= '<br />' . $data['back_express_time'] . '：产品已回寄';
            }
            if ($data['is_send_back'] == 3) {
                $log .= '<br />' . $data['back_receive_time'] . '：回寄产品已收货';
            }
            if ($data['shopping_state'] == 2) {
                $log .= '<br />' . $data['shopping_time'] . '：换货产品已发货';
                $log .= '<br />发货物流：' . $data['express'];
                $log .= '<br />发货单号：' . $data['express_no'];
            }
            if ($data['returned_state'] != 1) {
                $state_text = $data['returned_state'] == 2 ? '同意' : '拒绝';
                $log .= '<br />' . $data['state_time'] . '：' . $type_text . '流程已完成，状态：' . $state_text . $type_text;
            }
        }
        return $log;
    }

    public function ajaxSelect()
    {
        $return['data'] = $this->ajaxList();
        $return['count'] = $this->ajaxCount();
        return $return;
    }

    public function ajaxList()
    {
        $data = $this->order('returned_id desc')
            ->page($this->param['page'], $this->param['limit'])
            ->cache($this->cache_name('returned_list'), 86400, 'returned')
            ->select();
        if (! $data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data[$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    public function ajaxCount()
    {
        $count = $this->cache($this->cache_name('returned_count'), 86400, 'returned')
            ->count();
        return $count;
    }
    // 数据处理
    protected function handleData($val)
    {
        foreach ($val as $k => $v) {
            $val[$k] = $v;
            switch ($k) {
                case 'goods_sku':
                    $goodsdb = new Goodsdb();
                    $get_goods = $goodsdb->where('goods_sku',$v)->find();
                    $val['goods_name'] = $get_goods['goods_name'] ?? '产品已删除';
                    break;
                case 'back_express':
                    $val['back_express'] = changeExpress($v);
                    break;
                case 'express_id':
                    if ($v && $v > 0) {
                        $expressdb = new Expressdb();
                        $expressdb->param['express_id'] = $v;
                        $get_express = $expressdb->ajaxFind();
                        if ($get_express) {
                            $val['express'] = changeExpress($get_express['express']);
                            $val['express_no'] = $get_express['express_no'];
                        } else {
                            $val['express'] = '已删除';
                            $val['express_no'] = '已删除';
                        }
                    } else {
                        $val['express'] = '';
                        $val['express_no'] = '';
                    }
                default:
                    break;
            }
        }
        return $val;
    }
}